package com.cneport.das.common.security.pub;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * <p>标题：AES 加密工具</p>
 * <p>功能：</p>
 * <p>
 * 其他说明：
 * </p>
 * <p>作者：caoyuwu</p>
 * <p>审核：</p>
 * <p>重构：</p>
 * 查看帮助：<a href="" target="_blank"></a>
 */
public class AESValueEncoder implements java.io.Serializable
{
	final  protected java.security.Key key;

	public AESValueEncoder(java.security.Key key)
	{
		this.key = key;
	}
	public AESValueEncoder(byte key[])
	{
		this.key = buildAESKey(key);
	}


	public static java.security.Key newKey(){
		try {
			KeyGenerator kg = KeyGenerator.getInstance("AES");
			return kg.generateKey();
		} catch( NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex);
		}
	}

	public static java.security.Key buildAESKey(byte key[])
	{
		return new javax.crypto.spec.SecretKeySpec(key, "AES");
	}
	
	public static java.security.Key buildAESKey(String key) 
	{
		try {
		KeyGenerator _generator = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
        _generator.init(128, secureRandom);
        return _generator.generateKey();
		} catch( NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex);
		}
	}

	public byte[] getEncodedKey()
	{
		return key.getEncoded();
	}

	public byte[] encode(byte[] value)
	{
		try {
			Cipher cp = Cipher.getInstance("AES");
			cp.init(Cipher.ENCRYPT_MODE, key);
			return cp.doFinal(value);
		} catch( Throwable ex)
		{
			throw new RuntimeException(ex);
		}
	}

	public byte[] decode(byte[] value)
	{
		try {
			Cipher cp = Cipher.getInstance("AES");
			cp.init(Cipher.DECRYPT_MODE, key);
			return cp.doFinal(value);
		} catch( Throwable ex)
		{
			throw new RuntimeException(ex);
		}
	}
	/**
	 *
	 */
	private static final long serialVersionUID = -5701333725183548608L;
	
}
